package com.banmoon.question;

/**
 * 使用线程循环输出ABC
 */
public class Question1 {

    public static void main(String[] args) throws InterruptedException {
        Object a = new Object();
        Object b = new Object();
        Object c = new Object();
        ABC A = new ABC("A", c, a);
        ABC B = new ABC("B", a, b);
        ABC C = new ABC("C", b, c);

        new Thread(A).start();
        Thread.sleep(10);// 保证初始ABC的启动顺序
        new Thread(B).start();
        Thread.sleep(10);
        new Thread(C).start();
        Thread.sleep(10);
    }

}

class ABC implements Runnable{

    private String name;
    // 下一个获取的对象
    private Object prev;
    // 当前对象
    private Object self;

    public ABC(String name, Object prev, Object self) {
        this.name = name;
        this.prev = prev;
        this.self = self;
    }

    @Override
    public void run() {
        while (true){
            // 获取上个对象的锁
            synchronized (prev) {
                // 获取当前对象的锁
                synchronized (self) {
                    System.out.print(name);
                    // 唤醒当前对象锁，也就是下个线程的上个对象锁
                    self.notifyAll();
                }
                try {
                    Thread.sleep(50);
                    // 释放上个对象的锁
                    prev.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}